package handlers

import (
	"errors"
	"net/http"

	"github.com/AiGenApps/goout-server/models"
	"github.com/AiGenApps/goout-server/services"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type UserHandler struct {
	userService *services.UserService
}

func NewUserHandler() *UserHandler {
	return &UserHandler{
		userService: services.NewUserService(),
	}
}

func (h *UserHandler) Register(c *gin.Context) {
	var req models.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		var ve validator.ValidationErrors
		if errors.As(err, &ve) {
			out := make([]string, len(ve))
			for i, fe := range ve {
				out[i] = translateFieldError(fe)
			}
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数", "details": out})
			return
		}
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	ctx := c.Request.Context()
	user, err := h.userService.Register(ctx, &req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"message": "注册成功",
		"user":    user,
	})
}

func (h *UserHandler) Login(c *gin.Context) {
	var req models.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		var ve validator.ValidationErrors
		if errors.As(err, &ve) {
			out := make([]string, len(ve))
			for i, fe := range ve {
				out[i] = translateFieldError(fe)
			}
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数", "details": out})
			return
		}
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	ctx := c.Request.Context()
	response, err := h.userService.Login(ctx, &req)
	if err != nil {
		c.JSON(http.StatusUnauthorized, models.Error(401001, err.Error()))
		return
	}

	c.JSON(http.StatusOK, models.Success("登录成功", response))
}

func (h *UserHandler) GetCurrentUser(c *gin.Context) {
	userID, _ := c.Get("userID")
	username, _ := c.Get("username")

	c.JSON(http.StatusOK, models.Success("获取成功", gin.H{
		"user_id":  userID,
		"username": username,
	}))
}

func (h *UserHandler) ValidateToken(c *gin.Context) {
	userID, _ := c.Get("userID")
	username, _ := c.Get("username")

	var user models.User
	err := h.userService.GetUserByID(c.Request.Context(), userID.(string), &user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, models.Error(500001, "获取用户信息失败"))
		return
	}

	c.JSON(http.StatusOK, models.Success("Token有效", gin.H{
		"user_id":  userID,
		"username": username,
		"nickname": user.Nickname,
		"theme":    user.Theme,
	}))
}

func (h *UserHandler) UpdateProfile(c *gin.Context) {
	var req models.UpdateProfileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		var ve validator.ValidationErrors
		if errors.As(err, &ve) {
			out := make([]string, len(ve))
			for i, fe := range ve {
				out[i] = translateFieldError(fe)
			}
			c.JSON(http.StatusBadRequest, models.Error(400001, "无效的请求参数"))
			return
		}
		c.JSON(http.StatusBadRequest, models.Error(400001, "无效的请求参数"))
		return
	}

	userID, _ := c.Get("userID")
	err := h.userService.UpdateProfile(c.Request.Context(), userID.(string), &req)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.Error(400002, err.Error()))
		return
	}

	c.JSON(http.StatusOK, models.Success("更新成功", nil))
}

func translateFieldError(fe validator.FieldError) string {
	switch fe.Tag() {
	case "required":
		return fe.Field() + " 是必填项"
	case "min":
		return fe.Field() + " 最少需要 " + fe.Param() + " 个字符"
	case "max":
		return fe.Field() + " 最多允许 " + fe.Param() + " 个字符"
	default:
		return fe.Field() + " 不符合要求"
	}
}
